package com.github.controller;

import com.github.bean.AdminUser;
import com.github.pojo.HttpResult;
import com.github.service.AdminUserServer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/api/admin")
public class AdminController {

    @Autowired
    private AdminUserServer adminUserServer;

    /**
     * 分页查询后台用户
     */
    @GetMapping("/users")
    public Map<String, Object> getAdminUsers(
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size
    ) {
        // 获取所有用户
        List<AdminUser> allUsers = adminUserServer.getAllAdminUsers();

        // 分页处理
        int start = page * size;
        int end = Math.min(start + size, allUsers.size());
        List<AdminUser> pageUsers = allUsers.subList(start, end);

        // 构造分页对象
        Map<String, Object> response = new HashMap<>();
        response.put("content", pageUsers);
        response.put("totalPages", (int) Math.ceil((double) allUsers.size() / size));
        response.put("totalElements", allUsers.size());

        return response;
    }

    @PostMapping("/addUser")
    public HttpResult addAdminUser(@RequestBody AdminUser adminUser) {
        if (adminUserServer.addAdminUser(adminUser.getAccount(), adminUser.getPassword())) {
            return new HttpResult("添加成功");
        }
        return new HttpResult("添加失败");
    }

    @PostMapping("/delUser")
    public HttpResult delAdminUser(@RequestBody AdminUser adminUser) {
        if (adminUserServer.delAdminUser(adminUser.getAccount())) {
            return new HttpResult("删除成功");
        }
        return new HttpResult("删除失败");
    }
}
